<template>
  <el-dialog v-model="dialogVisibleInner" title="详情" @close="handlerClose">
    <div class="upload-corner">
      <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :auto-upload="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :show-file-list="false"
          :on-change="handleAvatarChange"
          :before-upload="beforeAvatarUpload"
          ref="uploadRef"
      >
        <div class="uploader-container">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <div v-else class="uploader-placeholder">
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            <span>点击上传</span>
          </div>
        </div>
      </el-upload>
    </div>
    <div class="dialog-content">
      <!-- 新增上传图片组件，放置在右上角 -->
      <!-- 新增上传图片组件，放置在右上角 -->

      <h3 class="title">个人信息详情</h3>

      <!-- 表单区域 -->
      <el-form :model="personalInfoForm" :rules="rules" ref="personalInfoFormRef" label-width="120px" style="max-width: 800px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="personalInfoForm.investors.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否为顾客" prop="isCustomer">
              <el-select v-model="personalInfoForm.investors.isCustomer" placeholder="请选择">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投资类型" prop="investmentType">
              <el-input v-model="personalInfoForm.investors.investmentType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="personalInfoForm.investors.gender" placeholder="请选择">
                <el-option label="男" :value="1"></el-option>
                <el-option label="女" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="居住地址" prop="residenceAddress">
              <el-input v-model="personalInfoForm.investors.residenceAddress"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话号码" prop="phoneNumber">
              <el-input v-model="personalInfoForm.investors.phoneNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联客户" prop="relatedCustomer">
              <el-input v-model="personalInfoForm.investors.relatedCustomer"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投资金额" prop="investmentAmount">
              <el-input-number v-model="personalInfoForm.investors.investmentAmount" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCardNumber">
              <el-input v-model="personalInfoForm.investors.idCardNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="照片路径" prop="photoPath">
              <el-input v-model="personalInfoForm.investors.photoPath"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 投资者信息 -->
      <el-divider content-position="left">投资者信息</el-divider>
      <el-button type="primary" @click="addInvestorRow">新增投资者</el-button>
      <el-table :data="personalInfoForm.investorsvoZbs" border style="width: 100%">
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="stationName" label="充电站名称" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.stationName"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="stationProperty" label="充电站属性" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.stationProperty"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="stationType" label="充电站类型" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.stationType"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="chargingPileCount" label="充电桩数量" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.chargingPileCount" controls-position="right" :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="详细地址">
          <template #default="scope">
            <el-input v-model="scope.row.address"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <!-- 项目信息 -->
      <el-divider content-position="left">项目信息</el-divider>
      <el-button type="primary" @click="addProjectRow">新增项目</el-button>
      <el-table :data="personalInfoForm.projects" border style="width: 100%">
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.projectName"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="projectDescription" label="项目描述">
          <template #default="scope">
            <el-input v-model="scope.row.remarks"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <!-- 操作按钮 -->
      <div class="dialog-actions">
        <el-button type="primary" @click="submitForm(personalInfoFormRef)">保存</el-button>
        <el-button @click="resetForm(personalInfoFormRef)">重置</el-button>
      </div>
      <el-dialog v-model="dialogS" >
      <Stiation2  :dialogS="dialogS" @StiationClose="StiationClose" @confirmSelection="confirmSelection"/>
      </el-dialog>
    </div>

  </el-dialog>

</template>

<script setup>
import { reactive, ref, onMounted, toRaw, defineProps, watch, defineEmits } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import Stiation2 from "./Stiation2.vue";

const  confirmSelection=(vel=>{
  personalInfoForm.value.investorsvoZbs=vel
  console.log( personalInfoForm.value.investorsvoZbs)
})
const StiationClose =(vel=>{
  dialogS.value=vel
})
const file=ref(null)
const handleAvatarChange=file1=>{
  imageUrl.value = URL.createObjectURL(file1.raw)
  file.value=file1.raw

}

const imageUrl=ref(null)
const uploadUrl = 'http://localhost:8080/upload/images'

const emit = defineEmits();
const handlerClose = () => {
  imageUrl.value=null
  dialogVisibleInner.value = false;
  // 告诉父组件，当前子组件关闭了
  emit('aclose', false);
};

const props = defineProps({
  dialog4add: Boolean // 是否可见
});

watch(() => props.dialog4add, (newVal) => {
  dialogVisibleInner.value = newVal;
});

const dialogVisibleInner = ref(false);

// 初始化 personalInfoForm 并设置默认值
const personalInfoForm = ref({
  investors: {
    name: '',
    isCustomer: null,
    investmentType: '',
    gender: null,
    residenceAddress: '',
    phoneNumber: '',
    relatedCustomer: '',
    investmentAmount: null,
    idCardNumber: '',
    photoPath: '',
    photoList: [] // 图片列表
  },
  investorsvoZbs: [], // 确保初始化为空数组
  projects: [] // 确保初始化为空数组
});
const dialogS=ref(false)
// 动态添加投资者行
const addInvestorRow = () => {
  dialogS.value=true
};

// 动态添加项目行
const addProjectRow = () => {
  personalInfoForm.value.projects.push({
    projectName: '',
    projectDescription: ''
  });
};

const router = useRoute();
onMounted(() => {});

const personalInfoFormRef = ref(null);

// 表单验证规则
// const rules = {
//   name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
//   isCustomer: [{ required: true, message: '请选择是否为顾客', trigger: 'change' }],
//   investmentType: [{ required: true, message: '请输入投资类型', trigger: 'blur' }],
//   gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
//   residenceAddress: [{ required: true, message: '请输入居住地址', trigger: 'blur' }],
//   phoneNumber: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
//   investmentAmount: [{ required: true, message: '请输入投资金额', trigger: 'blur' }],
//   idCardNumber: [{ required: true, message: '请输入身份证号', trigger: 'blur' }]
// };
const uploadRef=ref(null)
// 提交表单
const handleUploadSuccess = (response, uploadFile, fileList) => {
  console.log(response)
  personalInfoForm.value.investors.photoPath=response
};

const handleUploadError = (error, uploadFile, fileList) => {
alert("2")
};


const submitForm = async (formEl) => {
  let formDatr = new FormData;
  formDatr.append('file', file.value);
  const resp = await axios.post('/upload/images',formDatr);

  console.log(resp)

  personalInfoForm.value.investors.photoPath=resp.data
  const formData = toRaw(personalInfoForm.value);
  await axios.post('/Investors/addInvestors', formData)
      .then(resp => {
        ElMessage.success("添加成功");
        personalInfoForm.value={
          investors: {
            name: '',
            isCustomer: null,
            investmentType: '',
            gender: null,
            residenceAddress: '',
            phoneNumber: '',
            relatedCustomer: '',
            investmentAmount: null,
            idCardNumber: '',
            photoPath: ''
          },
          investorsvoZbs: [],
          projects: []
        }
        handlerClose();
      })
      .catch(error => {
        console.error('Error adding personal info:', error);
      });

}
// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped>
.dialog-content {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: var(--text-color);
  padding: 20px;
  position: relative; /* 确保内部元素可以相对于它定位 */

}

.title {
  font-size: 1.2em;
  margin: 0;
  padding: 0;
  margin-bottom: 20px;
}

.upload-corner {
  position: absolute;
  top: 1px;
  right: 40px;
}

.avatar-uploader .uploader-container {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-uploader .uploader-container:hover {
  border-color: #409eff;
}

.avatar-uploader .uploader-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.avatar-uploader .uploader-placeholder span {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.dialog-actions {
  text-align: right;
  margin-top: 20px;
}

/* 添加一些额外的样式来增强美观性 */
.el-form-item {
  margin-bottom: 16px;
}

.el-table {
  margin-top: 20px;
}

.el-divider {
  margin: 20px 0;
}
</style>